import service from '../utils/axios'
import type { ApiResponse } from '../utils/axios'

// 可参加的考试信息
export interface AvailableExam {
  paperId: number
  paperName: string
  courseId: number
  duration: number
  startTime: string
  endTime: string
  examId: number | null
  examStatus: 'not_started' | 'in_progress' | 'finished'
}

// 考试题目信息
export interface ExamQuestion {
  id: number
  type: 'single' | 'multiple' | 'judge' | 'fill' | 'essay'
  content: string
  options?: Record<string, string>
  score: number
  difficulty: 'easy' | 'medium' | 'hard'
  answer?: string
}

// 考试信息
export interface ExamInfo {
  examId: number
  paperName: string
  startTime: string
  endTime: string
  duration: number
  questions: ExamQuestion[]
}

// 题目结果信息
export interface QuestionResult {
  questionId: number
  type: 'single' | 'multiple' | 'judge' | 'fill' | 'essay'
  content: string
  options?: Record<string, string>
  correctAnswer: string
  studentAnswer: string
  score: number
  teacherComment: string
  analysis: string
}

// 考试结果
export interface ExamResult {
  examId: number
  paperName: string
  startTime: string
  endTime: string
  totalScore: number
  questions: QuestionResult[]
}

// 成绩信息
export interface ScoreInfo {
  examId: number
  paperName: string
  totalScore: number
  endTime: string
}

/**
 * 获取学生可参加的考试列表
 */
export function getAvailableExams(): Promise<ApiResponse<AvailableExam[]>> {
  return service({
    url: '/api/exams/available',
    method: 'get'
  })
}

/**
 * 开始考试
 */
export function startExam(paperId: number): Promise<ApiResponse<number>> {
  return service({
    url: `/api/exams/start/${paperId}`,
    method: 'post'
  })
}

/**
 * 获取考试题目
 */
export function getExamQuestions(examId: number): Promise<ApiResponse<ExamInfo>> {
  return service({
    url: `/api/exams/${examId}/questions`,
    method: 'get'
  })
}

/**
 * 保存答案
 */
export function saveAnswer(examId: number, questionId: number, content: string): Promise<ApiResponse<void>> {
  return service({
    url: `/api/exams/${examId}/answers`,
    method: 'post',
    data: {
      questionId,
      content
    }
  })
}

/**
 * 提交考试
 */
export function submitExam(examId: number): Promise<ApiResponse<void>> {
  return service({
    url: `/api/exams/${examId}/submit`,
    method: 'post'
  })
}

/**
 * 获取考试结果
 */
export function getExamResult(examId: number): Promise<ApiResponse<ExamResult>> {
  return service({
    url: `/api/exams/${examId}/result`,
    method: 'get'
  })
}

/**
 * 获取我的考试成绩列表
 */
export function getMyScores(): Promise<ApiResponse<ScoreInfo[]>> {
  return service({
    url: '/api/exams/my-scores',
    method: 'get'
  })
}

// 考试记录信息（管理员/教师查看）
export interface ExamRecord {
  examId: number
  paperId: number
  paperName: string
  studentId: number
  studentName: string
  studentUsername: string
  startTime: string
  endTime: string
  status: string
  totalScore: number | null
}

// 考试详情（管理员/教师查看）
export interface ExamDetail extends ExamResult {
  studentId: number
  studentName: string
  studentUsername: string
  status: string
}

/**
 * 管理员/教师：获取某个试卷的所有考试记录
 */
export function getPaperExamRecords(paperId: number): Promise<ApiResponse<ExamRecord[]>> {
  return service({
    url: `/api/exams/paper/${paperId}/records`,
    method: 'get'
  })
}

/**
 * 管理员/教师：查看某个学生的考试详情
 */
export function getExamDetail(examId: number): Promise<ApiResponse<ExamDetail>> {
  return service({
    url: `/api/exams/${examId}/detail`,
    method: 'get'
  })
}

// 待判卷考试信息
export interface PendingGradingExam {
  examId: number
  paperId: number
  paperName: string
  studentId: number
  studentName: string
  studentUsername: string
  endTime: string
  ungradedCount: number
}

// 判卷题目信息
export interface GradingQuestion {
  questionId: number
  type: 'single' | 'multiple' | 'judge' | 'fill' | 'essay'
  content: string
  options?: Record<string, string>
  correctAnswer: string
  analysis?: string
  maxScore: number
  studentAnswer: string
  score: number
  teacherComment: string
}

// 判卷详情信息
export interface GradingDetail {
  examId: number
  paperId: number
  paperName: string
  studentId: number
  studentName: string
  studentUsername: string
  startTime: string
  endTime: string
  questions: GradingQuestion[]
}

/**
 * 管理员/教师：获取待判卷考试列表
 */
export function getPendingGradingExams(): Promise<ApiResponse<PendingGradingExam[]>> {
  return service({
    url: '/api/exams/pending-grading',
    method: 'get'
  })
}

/**
 * 管理员/教师：获取某个考试的答案（用于判卷）
 */
export function getExamForGrading(examId: number): Promise<ApiResponse<GradingDetail>> {
  return service({
    url: `/api/exams/${examId}/grading`,
    method: 'get'
  })
}

/**
 * 管理员/教师：批量保存评分和评语
 */
export function saveGrading(examId: number, gradingData: Array<{ questionId: number, score: number, teacherComment: string }>): Promise<ApiResponse<void>> {
  return service({
    url: `/api/exams/${examId}/grading`,
    method: 'post',
    data: gradingData
  })
}

/**
 * 管理员/教师：获取所有学生考试记录
 */
export function getAllExamRecords(params?: { paperId?: number, studentId?: number }): Promise<ApiResponse<ExamRecord[]>> {
  // 过滤掉 undefined 值
  const cleanParams: Record<string, number> = {}
  if (params?.paperId !== undefined && params.paperId !== null) {
    cleanParams.paperId = params.paperId
  }
  if (params?.studentId !== undefined && params.studentId !== null) {
    cleanParams.studentId = params.studentId
  }
  
  return service({
    url: '/api/exams/all-records',
    method: 'get',
    params: Object.keys(cleanParams).length > 0 ? cleanParams : undefined
  })
}

// 成绩统计信息
export interface StatisticsData {
  paperId: number
  paperName: string
  totalCount: number
  scoredCount: number
  avgScore: number
  maxScore: number
  minScore: number
  passCount: number
  excellentCount: number
  goodCount: number
  passLowCount: number
  failCount: number
  passRate: number
}

/**
 * 管理员/教师：获取成绩统计信息
 */
export function getStatistics(paperId?: number): Promise<ApiResponse<StatisticsData[]>> {
  const params: Record<string, number> = {}
  if (paperId !== undefined && paperId !== null) {
    params.paperId = paperId
  }
  
  return service({
    url: '/api/exams/statistics',
    method: 'get',
    params: Object.keys(params).length > 0 ? params : undefined
  })
}

// 作弊行为记录
export interface CheatingBehavior {
  type: 'switch_window' | 'dev_tools' | 'copy_paste' | 'context_menu' | 'other'
  count?: number
  timestamp: string
}

/**
 * 记录作弊行为
 */
export function recordCheatingBehavior(examId: number, behavior: CheatingBehavior): Promise<ApiResponse<void>> {
  return service({
    url: `/api/exams/${examId}/cheating`,
    method: 'post',
    data: behavior
  })
}

